package com.zhouxin.customview.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.util.AttributeSet
import android.view.View
import com.zhouxin.customview.extensions.dp2px

/**
 * Copyright©
 * FileName: SportView
 * Author: ZhouXin
 * Date: 2022/6/6
 * Description: 绘制文字，居中，左对齐，上对齐
 * Tips:
 * paint.getTextBounds  --->静态测量,更准确
 * paint.getFontMetrics  ---->动态测量，大致准确
 */
private val CIRCLE_COLOR = Color.parseColor("#90A4AE")
private val HIGHLIGHT_COLOR = Color.parseColor("#FF4081")
private val RING_WIDTH = 20.dp2px
private val RADIUS = 150.dp2px

class SportView(context: Context?, attrs: AttributeSet?) : View(context, attrs) {
    private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        textSize = 100.dp2px
        textAlign = Paint.Align.CENTER
    }
    private val bounds = Rect()
    private val fontMetrics = Paint.FontMetrics()
    override fun onDraw(canvas: Canvas) {
        //绘制环
        paint.style = Paint.Style.STROKE
        paint.color = CIRCLE_COLOR
        paint.strokeWidth = RING_WIDTH
        canvas.drawCircle(width / 2f, height / 2f, RADIUS, paint)
        //绘制进度条
        paint.color = HIGHLIGHT_COLOR
        //设置线条的两端形状
        paint.strokeCap = Paint.Cap.ROUND
        canvas.drawArc(
            width / 2f - RADIUS,
            height / 2f - RADIUS,
            width / 2f + RADIUS,
            height / 2f + RADIUS,
            -90f, 260f, false, paint
        )
        //绘制文字
        paint.style = Paint.Style.FILL
        //静态测量
//        paint.getTextBounds("abap", 0, "abab".length, bounds)
//        canvas.drawText("abap", width / 2f, height / 2f - (bounds.top + bounds.bottom) / 2f, paint)
        //动态测量
        paint.getFontMetrics(fontMetrics)
        canvas.drawText(
            "abab",
            width / 2f,
            height / 2f - (fontMetrics.ascent + fontMetrics.descent) / 2f,
            paint
        )

        //绘制文字2
        paint.textSize = 150.dp2px
        paint.getFontMetrics(fontMetrics)
        paint.getTextBounds("abab", 0, "abab".length, bounds)
        paint.textAlign = Paint.Align.LEFT
        canvas.drawText("abab", -bounds.left.toFloat(), -fontMetrics.top, paint)

        //绘制文字3
        paint.textSize = 15.dp2px
        paint.getFontMetrics(fontMetrics)
        paint.getTextBounds("abab", 0, "abab".length, bounds)
        paint.textAlign = Paint.Align.LEFT
        canvas.drawText("abab", -bounds.left.toFloat(), -bounds.top.toFloat(), paint)
    }
}